package com.wxc.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wxc.common.utils.PageUtils;
import com.wxc.common.utils.Query;
import com.wxc.product.dao.CategoryDao;
import com.wxc.product.entity.CategoryEntity;
import com.wxc.product.service.CategoryService;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        // 查出所有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);

        // 获得一级分类
        List<CategoryEntity> level1Menus = entities.stream()
                // 过滤 null
                .filter(categoryEntity -> categoryEntity.getParentCid() != null)
                // 一级分类
                .filter(categoryEntity -> categoryEntity.getParentCid() == 0)
                // 添加子菜单
                .peek(categoryEntity -> {
                    categoryEntity.setChildren(getChildren(categoryEntity, entities));
                    if(categoryEntity.getSort() == null) {
                        categoryEntity.setSort(Integer.MAX_VALUE);
                    }
                })
                // 排序
                .sorted(Comparator.comparingInt(CategoryEntity::getSort))
                .collect(Collectors.toList());
        // 组装分类
        return level1Menus;
    }

    /**
     * 递归查找子菜单
     */
    private List<CategoryEntity> getChildren(CategoryEntity root, List<CategoryEntity> categoryEntities) {
        return categoryEntities
                .stream()
                .filter(categoryEntity -> categoryEntity.getParentCid() != null)
                .filter(categoryEntity -> categoryEntity.getParentCid().equals(root.getCatId()))
                .peek(categoryEntity -> {
                    categoryEntity.setChildren(getChildren(categoryEntity, categoryEntities));
                    if(categoryEntity.getSort() == null) {
                        categoryEntity.setSort(Integer.MAX_VALUE);
                    }
                })
                .sorted(Comparator.comparingInt(CategoryEntity::getSort))
                .collect(Collectors.toList());
    }
}